﻿using Enter.Admin.Constant;
using Enter.Admin.Models;
using FluentValidation.Results;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Enter.Admin.Filters
{
    public class ValidatorFilter : IActionFilter
    {
        public void OnActionExecuting(ActionExecutingContext context)
        {
            if (!context.HttpContext.Items.TryGetValue(Constants.FluentValidationResult, out var value))
            {
                return;
            }
            if (!(value is ValidationResult vldResult))
            {
                return;
            }
            var errors = vldResult.Errors.Select(t => t.ErrorMessage).ToList();
            var result = new ResponseResult<List<string>>
            {
                Success = false,
                Data = errors,
                Message = string.Join(",", errors.Select(e => string.Format("{0}", e))),
            };
            context.Result = new JsonResult(result);

            //if (!context.ModelState.IsValid)
            //{
            //    var errors = context.ModelState
            //      .Values
            //      .SelectMany(x => x.Errors
            //            .Select(p => p.ErrorMessage))
            //      .ToList();
            //    var result = new ResponseResult<List<string>>
            //    {
            //        Success = false,
            //        Data = errors,
            //        Message = string.Join(",", errors.Select(e => string.Format("{0}", e)).ToList()),
            //    };
            //    context.Result = new JsonResult(result);
            //}
        }

        public void OnActionExecuted(ActionExecutedContext context)
        {
            //filterContext.Result = new RedirectResult("customErrorPage.html");
            //context.HttpContext.Response.WriteAsync($"{GetType().Name} out. \r\n");
        }
    }
}
